/*
 * connection.h
 *
 *  Created on: 2021年1月27日
 *      Author: kimfeng
 */

#ifndef CONNECTION_H_
#define CONNECTION_H_

#include "asock_type.h"
#include "pkg_parser.h"
#include <logger.h>

#include <vector>
#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include "callback_handler.h"

class connection_manager;

class connection: public boost::enable_shared_from_this<connection>,
		private boost::noncopyable
{
public:
	explicit connection(boost::asio::io_service &io_service,
			connection_manager &manager, callback_handler& handler);

	void start(connection_id_t id);
	void stop();

	boost::asio::ip::tcp::socket& socket();

	connection_id_t get_id();

	void async_write(const sck_pkg_t *pkg);
	void async_write(uchar *buf, std::size_t n);

private:
	boost::asio::ip::tcp::socket m_sock;
	boost::array<uchar, 8192> m_buffer;

	void handle_read(const boost::system::error_code &e,
			std::size_t bytes_transferred);
	void handle_write(const boost::system::error_code& e, void *buf);

	void send_respond(const sck_pkg_t *pkg, const vec_data_t& rsp);

	void handle_rd_timeout();

	std::string m_endpoint;
	connection_manager & m_manager;
	pkg_parser m_parser;
	callback_handler & m_handler;

	boost::asio::deadline_timer m_timer;
	sck_pkg_t m_pkg;
	vec_data_t m_payload;

	connection_id_t m_id;
};

typedef boost::shared_ptr<connection> connection_ptr;

#endif /* CONNECTION_H_ */
